package com.zyms.tools;

import cn.jpush.api.device.TagAliasResult;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;


/**
 * java后台极光推送方式(Java SDK)
 */
public class JpushUtil {
    private static final Logger log = LoggerFactory.getLogger(JpushUtil.class);
    private static String masterSecret = "98b15d7349e64d4fab455690";
    private static String appKey = "e7cdaf5ae66e3607f53d5b13";
    private static String REGISTRATION_ID = "13065ffa4e02e26f81b"; //注册id
    private static final String ALERT = "纵意弥森23333";
    /**
     * 极光推送(所有)
     */
    public static void jiguangPushAll(String msg){
//        String alias = "13065ffa4e02e26f81b";//声明别名
//        log.info("对别名" + alias + "的用户推送信息");
        log.info("向所有的用户推送信息");
        msg = ALERT;
        PushResult result = pushAll(msg);
        if(result != null && result.isResultOK()){
            //log.info("针对别名" + alias + "的信息推送成功！");
            System.out.println("广播信息推送成功！");
        }else{
            //log.info("针对别名" + alias + "的信息推送失败！");
            System.out.println("广播信息推送失败！");
        }
    }
    /**
     * 极光推送(单个)
     */
    public static void jiguangPushByRegistrationId(String registrationId,String title,String msg){
        registrationId = REGISTRATION_ID;
        log.info("根据id>>>" + registrationId + "向用户推送信息");
        PushResult result = pushByRegistrationId(registrationId,title,msg);
        if(result != null && result.isResultOK()){
            log.info("针对ID为" + registrationId + "的信息推送成功！");
        }else{
            log.info("针对ID为" + registrationId + "的信息推送失败！");
        }
    }

    /**
     * 所有平台，所有设备，内容为 content 的通知
     *
     * @param content
     * @return
     */
    public static PushPayload buildPushObject_all_all_alert(String content) {
        return PushPayload.alertAll(content);
    }

    /**
     * 所有平台，推送目标是别名为 "alias1"
     * @return
     */
    public static PushPayload buildPushObject_all_alias_alert() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias("alias1"))
                .setNotification(Notification.alert(ALERT))
                .build();
    }
    /**
     * 生成极光推送对象PushPayload（采用java SDK）
     * android_ios平台，推送目标是别名为 "alias"
     * @param alias
     * @param alert
     * @return PushPayload
     */
    public static PushPayload buildPushObject_android_ios_alias_alert(String alias,String alert){
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(alias))//alias别名
                //.setAudience(Audience.tag(alias))//tag标签
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .addExtra("type", "infomation")
                                .setAlert(alert)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtra("type", "infomation")
                                .setAlert(alert)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
    }
    /**
     * 极光推送方法(采用java SDK)
     * @param alert
     * @return PushResult
     */
    public static PushResult pushAll(String alert){
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
        //别名
        //PushPayload payload = buildPushObject_android_ios_alias_alert(alias,alert);
        //广播
        PushPayload payload = buildPushObject_all_all_alert(alert);
        System.out.println("生成极光推送对象");
        try {
            return jpushClient.sendPush(payload);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
            e.printStackTrace();
            return null;
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
            log.info("Msg ID: " + e.getMsgId());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 极光推送方法(采用java SDK)
     * @param registrationId
     * @return PushResult
     */
    public static PushResult pushByRegistrationId(String registrationId,String title,String msg){
        registrationId = REGISTRATION_ID;
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
        System.out.println("生成极光推送对象");
        try {
            //根据REGISTRATION_ID获取别名和标签
            TagAliasResult result = jpushClient.getDeviceTagAlias(registrationId);
            log.info("alias>>>>>"+result.alias);
            log.info("tag>>>>>>"+result.tags.toString());
            //推送
            //return jpushClient.sendAndroidMessageWithRegistrationID(title,msg,registrationId);
            return jpushClient.sendAndroidNotificationWithRegistrationID(title,msg,null,registrationId);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
            e.printStackTrace();
            return null;
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
            log.info("Msg ID: " + e.getMsgId());
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        PropertyConfigurator.configure("D:\\lutao\\IdeaProjects\\chat\\src\\main\\resources\\conf\\log4j.properties");
        JpushUtil.jiguangPushByRegistrationId(REGISTRATION_ID,"74867","mgorjgqienut956");
    }
}
